#!/usr/bin/env bash

FILE_PATH="${1}"
FILE_EXTENSION="${FILE_PATH##*.}"
FILE_EXTENSION_LOWER="$(printf "%s" "${FILE_EXTENSION}" | tr '[:upper:]' '[:lower:]')"
PV_WIDTH="${2}"
PV_HEIGHT="${3}"
HORIZONTAL_POS="${4}"
VERTICAL_POS="${5}"

image_preview_by_kitty() {
  kitten icat --clear --transfer-mode memory --stdin no --place \
      "${PV_WIDTH}x${PV_HEIGHT}@${HORIZONTAL_POS}x${VERTICAL_POS}" \
      "${1}" < /dev/null > /dev/tty
}

handle_extension() {
  case "${FILE_EXTENSION_LOWER}" in
    # Markdown
    md)
      glow -s dark -- "${FILE_PATH}" && exit 1;;
    # Archive
    bz2|gz|lz|tar|xz|zip)
      atool --list -- "${FILE_PATH}" && exit 1;;
    rar)
      unrar l -p- -- "${FILE_PATH}" && exit 1;;
    7z)
      7z l -p -- "${FILE_PATH}" && exit 1;;
    # PDF
    pdf)
      pdftotext -l 10 -nopgbrk -q -- "${FILE_PATH}" - | fmt -w "$((${PV_WIDTH} - 2))" && exit 1;;
    # OpenDocument
    odt|sxw|ods|odp)
      odt2txt "${FILE_PATH}" && exit 1;;
    # XLSX
    xlsx)
      xlsx2csv -- "${FILE_PATH}" && exit 1;;
    # JSON
    json)
      jq --color-output . "${FILE_PATH}" && exit1 ;;
    # BitTorrent
    torrent)
      transmission-show -- "${FILE_PATH}" && exit 1;;
  esac
}

handle_mime() {
  local mimetype="${1}"
  case "${mimetype}" in
    # DOCX, ePub, FB2
    *wordprocessingml.document|*/epub+zip|*/x-fictionbook+xml)
      pandoc -s -t markdown -- "${FILE_PATH}" && exit 1;;
    # Image
    image/*)
      if [[ $TERM == "xterm-kitty" ]]; then
        image_preview_by_kitty "${FILE_PATH}"
      else
        exiftool "${FILE_PATH}"
      fi
      exit 1;;
    # Video and audio
    video/* | audio/*)
      if [[ $TERM == "xterm-kitty" ]]; then
        local thumbnail=$($HOME/.config/lf/vidthumb "${FILE_PATH}")
        image_preview_by_kitty "${thumbnail}"
      else
        mediainfo "${FILE_PATH}"
      fi
      exit 1;;
    # Text
    text/* | */xml)
      (bat --color=always --style=numbers,changes --line-range=:"${PV_HEIGHT}" \
          --terminal-width "$((${PV_WIDTH} - 2))" -- "${FILE_PATH}" \
      || highlight --out-format truecolor --style darkplus --force \
          --line-numbers --line-range=1-"${PV_HEIGHT}" -- "${FILE_PATH}" \
      || cat -- "${FILE_PATH}") && exit 1;;
  esac
}

handle_fallback() {
    echo '----- File Type Classification -----' && file --dereference --brief -- "${FILE_PATH}" && exit 1
    exit 1
}

MIMETYPE="$( file --dereference --brief --mime-type -- "${FILE_PATH}" )"
handle_extension
handle_mime "${MIMETYPE}"
handle_fallback

exit 1
